package com.yzf.demo.demo.Thread.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by 于占峰 on 2020/4/4/004.
 * <p>
 * ReentrantReadWriteLock读写锁
 * StampedLock 读写锁的完善升级
 */
public class LockDemo {

    public static int count = 0;
    /**
     * 声明ReentrantLock锁  重入锁
     * public ReentrantLock() {
     * sync = new NonfairSync();
     * }
     */
    static Lock lock = new ReentrantLock();//默认非公平锁 效率高一些
    /**
     * public ReentrantLock(boolean fair) {
     * sync = fair ? new FairSync() : new NonfairSync();
     * }
     */
    static Lock lock2 = new ReentrantLock(true);//构造函数传入true 公平锁 效率会相对低一些

    public static void incr() {
        try {
            lock.lock();//获得锁
            Thread.sleep(1);
            count++;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }
    }

    /**
     * 开启1000个线程调用incr 自增count
     *
     * @param args
     */
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 1000; i++) {
            new Thread(LockDemo::incr).start();
        }
        Thread.sleep(4000);//让main主线程睡眠4秒 以便让所有线程都执行完毕 在结束主线程 打印结果
        System.out.println(count);
    }
}
